package com.liaoye.hellocustomview.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

public class PathGetLoadingView extends View {


    private Paint paint;
    private Path path;
    private final String TAG = PathGetLoadingView.class.getSimpleName();
    private Path dst;
    private PathMeasure pathMeasure;
    private float animatedValue;
    private int centerX;
    private int centerY;
    private int radius;
    private boolean hasContour;

    public PathGetLoadingView(Context context) {
        super(context);
        init();
    }

    public PathGetLoadingView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        setLayerType(LAYER_TYPE_SOFTWARE, null);
        //设置画笔的基本属性
        paint = new Paint();
        //设置画笔颜色
        paint.setColor(Color.RED);
        //设置填充样式
        paint.setStyle(Paint.Style.STROKE);
        //设置画笔宽度
        paint.setStrokeWidth(5);

        path = new Path();
        pathMeasure = new PathMeasure();
        dst = new Path();

        centerX = 400 / 2;
        centerY = 400 / 2;

        radius = 400 / 4;
        Log.i(TAG, "init: centerX = " + centerX + " centerY = " + centerY + " radius =" + radius);

        path.addCircle(centerX, centerY, radius, Path.Direction.CW);


        path.moveTo(centerX - radius / 2, centerY);
        path.lineTo(centerX, centerY + radius / 2);
        path.lineTo(centerX + radius / 2, centerY - radius / 2);


        pathMeasure.setPath(path, false);


        ValueAnimator animator = ValueAnimator.ofFloat(0, 2);
        animator.addUpdateListener(animation -> {
            animatedValue = (float) animator.getAnimatedValue();
            invalidate();
        });
        animator.setDuration(2000);
        animator.start();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (animatedValue < 1) {
            float stop = animatedValue * pathMeasure.getLength();
            pathMeasure.getSegment(0, stop, dst, true);
        } else {
            if (!hasContour) {
                pathMeasure.getSegment(0, pathMeasure.getLength(), dst, true);
                pathMeasure.nextContour();
                hasContour = true;
            }
            float stop = (animatedValue - 1) * pathMeasure.getLength();
            pathMeasure.getSegment(0, stop, dst, true);
        }
        canvas.drawPath(dst, paint);
    }
}
